//
//  CS_WifiManager.swift
//  NewSS
//
//  Created by 杨馥瑞 on 2021/9/7.
//

import UIKit

class CS_WifiManager: NSObject, CS_WifiTransferServicesDelegate {
    
    private var _service: CS_WIFITransferServices?
    var displayURL: String { _service?.displayURL ?? "" }
    weak var delegate: CS_WifiManagerDelegate?
    
    deinit {
        stop()
    }
    
    // MARK: - 外部方法
    
    func start() {
        _service = CS_WIFITransferServices()
        _service?.delegate = self
        _service?.start()
    }
    
    func stop() {
        _service?.stop()
        _service = nil
    }
    
    // MARK: - CS_WifiTransferServicesDelegate
    
    func transferServicesDidStart(_ service: CS_WIFITransferServices) {
        delegate?.wifiManagerDidStart(self)
    }
    
    func transferServicesDidReceiveConnect(_ service: CS_WIFITransferServices) {
        
    }
    
    func transferServices(_ service: CS_WIFITransferServices, didRequestAcess ipAddress: String) {
        service.allowClientAccess(ipAddress)
    }
    
    func transferServices(_ service: CS_WIFITransferServices, didReceiveSendingFile file: CS_WifiTransferFileItem) {
        delegate?.wifiManager(self, beginReceive: file)
    }
    
    func transferServices(_ service: CS_WIFITransferServices, didRecieveFileSuccess file: CS_WifiTransferFileItem) {
        delegate?.wifiManager(self, endReceive: file, isSuccess: true)
        CJLogI("Upload file success \(file.fileName)")
    }
    
    func transferServices(_ service: CS_WIFITransferServices, didRecieveFileFail file: CS_WifiTransferFileItem) {
        delegate?.wifiManager(self, endReceive: file, isSuccess: false)
        CJLogI("Upload file failed \(file.fileName)")
    }
    
    func transferServicesDidDisConnect(_ service: CS_WIFITransferServices) {
        delegate?.wifiManagerDidDisConnected(self)
    }
    
}

protocol CS_WifiManagerDelegate: NSObjectProtocol {
    func wifiManagerDidStart(_ manager: CS_WifiManager)
    func wifiManager(_ manager: CS_WifiManager, beginReceive file: CS_WifiTransferFileItem)
    func wifiManager(_ manager: CS_WifiManager, endReceive file: CS_WifiTransferFileItem, isSuccess: Bool)
    func wifiManagerDidDisConnected(_ manager: CS_WifiManager)
}

extension CS_WifiManagerDelegate {
    func wifiManagerDidStart(_ manager: CS_WifiManager) {}
    func wifiManager(_ manager: CS_WifiManager, beginReceive file: CS_WifiTransferFileItem) {}
    func wifiManager(_ manager: CS_WifiManager, endReceive file: CS_WifiTransferFileItem, isSuccess: Bool) {}
    func wifiManagerDidDisConnected(_ manager: CS_WifiManager) {}
}
